﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Information;
using System.Web;
using System.Configuration;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// AGV避障时长统计报表运算
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class IWMSBZInfoController : ControllerBase
    {
        private readonly ILogger<IWMBZInfoRequestDto> _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_t;


        public IWMSBZInfoController(ILogger<IWMBZInfoRequestDto> logger,IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration)
        {
            _logger = logger;
            _WMSTokenCheckService = wmsTokenCheckService;
             con= _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_t = _configuration.GetConnectionString("WMSDbConnection_Test");

        }

        /// <summary>
        /// AGV避障时长统计报表运算
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostBzInfo([FromBody] IWMBZInfoRequestDto strparm)
        {
            string  strMsg = "";
            object log = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            IWMBZInfoResponseDto re = new IWMBZInfoResponseDto();
            string sqlstr = "";

            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
                dic.Add("machine_no", "");//查看URL配置表地址描述
                sqlstr = @"select ag.ID,m.workshop_code,m.workshop_name,ag.agvID,ag.traggerTime,ag.flag  from agv_obstacle ag left join iwsm_machine_file m on  ag.agvID=m.machine_no  left join  iwms_agv_bzinfo  bz  on  ag.id=bz.bzid  where 
ag.traggerTime>STR_TO_DATE(DATE(CURDATE() - INTERVAL 1 DAY),'%Y-%m-%d %H:%i:%s') and (bz.bzid is null or bz.bzid='' )and  ag.flag='避障' order by ag.agvID,ag.traggerTime  limit 500
  ";
                DataTable dt_b = DB.Query(sqlstr, con_t);//避障记录列表
                if (dt_b.Rows.Count>0)
                {
                    foreach (DataRow item in dt_b.Rows)
                    {
                        sqlstr = "";
                        string end_time = "";
                        string workshop_code = item["workshop_code"].ToString();
                        string workshop_name = item["workshop_name"].ToString();
                        string agvID = item["agvID"].ToString();
                        string traggerTime = item["traggerTime"].ToString();
                        string id = item["ID"].ToString();
                        string agv_workline = agvID.Substring(2,2);

                        sqlstr = @"select ag.ID,m.workshop_code,m.workshop_name,ag.agvID,ag.traggerTime,ag.flag  from agv_obstacle ag left join iwsm_machine_file m on  
ag.agvID=m.machine_no where ag.traggerTime>='"+ traggerTime + "' and ag.agvID='"+ agvID + "' and   flag='避障解除' order by ag.agvID,ag.traggerTime;";                       
                        DataTable dt_d = DB.Query(sqlstr, con_t);//运单明细
                        if (dt_d.Rows.Count>0)
                        {
                            end_time = dt_d.Rows[0]["traggerTime"].ToString();                                              
                        }

                        //开始结束时间计算时间
                        TimeSpan difference = DB.ToDateTime(end_time) - DB.ToDateTime(traggerTime);
                        double total_duration = Math.Round(difference.TotalMinutes,2);


                        sqlstr = @"insert into  iwms_agv_bzinfo(bzid,fault_type,agv_region,agv_workshop,agv_workline,start_time,end_time,interval_time,create_time,agvid) VALUES
("+ id + ",'避障','"+ workshop_code + "','"+ workshop_name + "','"+ agv_workline + "','"+ traggerTime + "','"+ end_time + "',"+ total_duration.ToString() + ",SYSDATE(),'"+ agvID + "');";

                        strSqlList.Add(sqlstr.ToString());
                        //插入数据库语句拼接
                        //dic = new Dictionary<string, string>();
                        //dic.Add("bzid", id);
                        //dic.Add("agv_region", workshop_code);
                        //dic.Add("agv_workshop", workshop_name);
                        //dic.Add("agv_workline", agv_workline);
                        //dic.Add("start_time", traggerTime);
                        //dic.Add("end_time", end_time);
                        //dic.Add("interval_time", total_duration.ToString());
                        //dic.Add("agvid", agvID);
                        //string strSQL = MethodHelp.GetTranSQL("TMS0029", dic, con);//转换插入数据库语句
                        //if (strSQL == "")
                        //{
                        //    strMsg = "TMS0029,Parameter conversion failed";
                        //}
                        //else
                        //{
                        //    strSqlList.Add(strSQL.ToString());
                        //}
                      
                    }
                    if (strSqlList.Count > 0)
                    {
                        bool A = DB.ExecuteNoQueryTran(strSqlList, con_t);
                    }
                }


            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

         


            if (strMsg=="")
            {
                re.code = 0;
               
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }


            return new JsonResult(re);
        }

      
    }
}
